package com.eden.manage.utils;


import com.eden.manage.config.ApplicationContextAwareFactory;
import com.eden.manage.dto.UserInfoDto;
import com.eden.manage.service.LoginService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

public class WebUserUtils {

    public static UserInfoDto getUserInfo(){
        String token = getHeadAttr("Authorization");
        String dbToken = token.replace("Bearer ","");
        LoginService loginService = ApplicationContextAwareFactory.getApplicationContext().getBean(LoginService.class);
        return loginService.getUserInfo(dbToken);

    }
    private static HttpServletRequest getRequest() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        return requestAttributes instanceof ServletRequestAttributes ? ((ServletRequestAttributes)requestAttributes).getRequest() : null;
    }

    private static String getHeadAttr(String attr) {
        HttpServletRequest request = getRequest();
        return request != null && !StringUtils.isEmpty(attr) ? request.getHeader(attr) : "";
    }


}
